//
//  PYShowMediaPresentAnimation.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "PYShowMediaPresentAnimation.h"
#import <AVFoundation/AVFoundation.h>
#import "PYShowMediaController.h"
#import "PYMediaInfo.h"

@implementation PYShowMediaPresentAnimation
// 返回动画的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    return PY_Animation_Duration;
}
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    UIViewController * fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PYShowMediaController * toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView * container = [transitionContext containerView];
    UIView *fromView;
    UIView *toView;
    
    if ([transitionContext respondsToSelector:@selector(viewForKey:)]) {
        fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    } else {
        fromView = fromVC.view;
        toView = toVC.view;
    }
    
    PYMediaInfo *mediaInfo = [toVC getCurrentModel];
    
    UIView *bgView = [UIView new];
    bgView.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
    bgView.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    bgView.alpha = 0;
    
    UIImageView *imgView = [UIImageView new];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.layer.masksToBounds = YES;
    if (mediaInfo) {
        imgView.image = mediaInfo.placeholderImg;
        imgView.frame = mediaInfo.imgViewFrame;
        imgView.layer.cornerRadius = mediaInfo.imgViewCornerRadius;
    }
    
    [[UIApplication sharedApplication].keyWindow addSubview:imgView];
    
    [UIView animateKeyframesWithDuration:[self transitionDuration:transitionContext] delay:0 options:2 animations:^{
        bgView.alpha = 1;
        CGRect frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        if (imgView.image.size.width != 0 && imgView.image.size.height != 0) {
            frame = AVMakeRectWithAspectRatioInsideRect(imgView.image.size, CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT));
        }
        imgView.frame = frame;
        imgView.layer.cornerRadius = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            [bgView removeFromSuperview];
            [imgView removeFromSuperview];
            [container addSubview:toView];
            
            BOOL wasCancelled = [transitionContext transitionWasCancelled];
            if (wasCancelled) {
                [toView removeFromSuperview];
            }
            [transitionContext completeTransition:!wasCancelled];
        }
    }];
}
@end
